//
//  PlayGitVC.swift
//  RKTemplate
//
//  Created by zhaoke on 2023/9/25.
//

import Foundation
import UIKit

class PlayGitVC: UIViewController {
    var imageView1: UIImageView?
    var imageView2: UIImageView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Gif"
        view.backgroundColor = .white
        setupChildView()
        loadGifImage(imageView: imageView1!, imageName: "demo.gif")
        loadGifImage(imageView: imageView2!, imageName: "demo1.gif")
    }
    func setupChildView() {
        let width = view.bounds.size.width
        let height = view.bounds.size.height
        imageView1 = UIImageView.init(frame: CGRect(x: 0, y: 100, width: width, height: (height-100) / 2))
        imageView2 = UIImageView.init(frame: CGRect(x: 0, y: height / 2 + 50, width: width, height: height / 2 - 50))
        view.addSubview(imageView1!)
        view.addSubview(imageView2!)
    }
    func loadGifImage(imageView: UIImageView, imageName: String) {
        guard let path = Bundle.main.path(forResource: imageName, ofType: nil) else { return }
        guard let data = NSData.init(contentsOfFile: path) else { return }
        guard let imageSource = CGImageSourceCreateWithData(data, nil) else { return }
        let imageCount = CGImageSourceGetCount(imageSource)
        var images = [UIImage]()
        var totalDuration: TimeInterval = 0
        for i in 0..<imageCount {
            guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { return }
            let image = UIImage(cgImage: cgImage)
            if i == 0 {
                imageView.image = image
            }
            images.append(image)
            guard let properities = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else { continue }
            guard let gifDict = (properities as NSDictionary)[kCGImagePropertyGIFDictionary] as? NSDictionary else { continue  }
            guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
            totalDuration += frameDuration.doubleValue
        }
        imageView.animationImages = images
        imageView.animationDuration = totalDuration
        imageView.animationRepeatCount = 10
        imageView.startAnimating()
    }
}
